package com.maduar.mybatis.demo.service;

import com.maduar.mybatis.demo.util.SpringUtils;
import com.maduar.mybatis.demo.vo.FactoryAppointmentInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 *
 * @author maduar maduar@163.com
 * @date 2021-04-18 00:49
 */
@Component
public class AppointmentFactoryStrategy {

    @Autowired
    private Environment environment;

    /**
     *  @Author: danny.pang
     *  @Date: 2021-04-18 10:5
     *  @Discription:   map - key: strategyId,从配置获取
     *                      - value: beanName,需要生成的bean的小写class名称
     *
     */
    public static Map<String, String> map = new HashMap<>();


    public <T> T getStrategy(String strategyId, Class<T> t) {
        if (StringUtils.isEmpty(strategyId)) {
            return null;
        }

        String beanName = getMap(strategyId);
        if (StringUtils.isEmpty(beanName)) {
            return null;
        }

        @SuppressWarnings("unchecked")
        T bean = (T) SpringUtils.getBean(beanName);
        return bean;
    }

    private String getMap(String strategyId) {
        if (CollectionUtils.isEmpty(map)) {
            init();
        }

        return map.get(strategyId);
    }

    private void init() {
        // 用于生成KafkaStrategy
        map.put(environment.getProperty(FactoryAppointmentInterface.FIRST), FactoryAppointmentInterface.FIRST_APPOINTMENT_STRATEGY);
        // 用于生成RabbitStrategy
        map.put(environment.getProperty(FactoryAppointmentInterface.SECOND), FactoryAppointmentInterface.SECOND_APPOINTMENT_STRATEGY);
    }
}
